package com.zt.questionnaire.common.msg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

@Data
public class HResultMsg {
	static Logger log = LoggerFactory.getLogger(HResultMsg.class);
	private int msgType = 1;
	private int errorCode = HErrorCode.SUCC;
	private String errorMsg;
	private Object size;
	private Object result;


	public static String createMsgSucc(){
		return createMsgSucc(null);
	}
	/**
	 * 返回字符串，不直接返回HResultMsg对象的原因是，control层如果直接返回对象的话，
	 * 对象里的null的属性值会返回到客户端，不会被过滤掉，例如errorMsg=null的时候，如果用json转成字符串后，errorMsg这个属性就不会给到客户端了
	 * @param result
	 * @return
	 */
	public static String createMsgSucc(Object result){
		HResultMsg msg = new HResultMsg();
		msg.result = result;
		if(log.isInfoEnabled()){
			log.info(JSONObject.toJSONString(msg));
		}
		return JSONObject.toJSONString(msg);
	}

	public static String createMsgSuccPage(Object result,Object size){
		HResultMsg msg = new HResultMsg();
		msg.result = result;
		msg.setSize(size);
		if(log.isInfoEnabled()){
			log.info(JSONObject.toJSONString(msg));
		}
		return JSONObject.toJSONString(msg);
	}

	public static String createMsgSucc(String name, Object value) {
		HResultMsg msg = new HResultMsg();
		msg.setResult(name, value);
		if(log.isInfoEnabled()) {
			log.info(JSONObject.toJSONString(msg));
		}
		return JSONObject.toJSONString(msg);
	}

	public static String createMsgError(int errorCode,String errorMsg){
		HResultMsg msg = new HResultMsg();
		msg.setErrorCode(errorCode);
		msg.setErrorMsg(errorMsg);
		if(log.isInfoEnabled()){
			log.info(JSONObject.toJSONString(msg));
		}
		return JSONObject.toJSONString(msg);
	}

	@SuppressWarnings("unchecked")
	public void setResult(String name, Object obj) {
		if(this.result == null) {
			this.result = new HashMap<String,Object>();
		}
		Map<String,Object> tmpResult = (Map<String, Object>) this.result;
		tmpResult.put(name, obj);
	}

	public String toJSONString() {
		return JSON.toJSONString(this);
	}
}
